﻿/*
Copyright (c) 2016 Robert Gaffney
Licensed under the MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/



using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Kemper_Duplicate_Finder
{
    class FileReader
    {
        public string path;
        public uint currentTagStart;
        private Boolean inTag;
        public List<MidiTag> tags;
        public Dictionary<string, MidiTag> tagDict;
        public Dictionary<string, MidiTag> profileTags;
        public bool newProfileFormat;
        public string ampHash;
        public string cabHash;

        public FileReader(string filePath)
        {
            this.path = filePath;
            //this.inTag = false;
        }

        public void parse()
        {
            this.inTag = false;
            this.tags = new List<MidiTag>();
            this.tagDict = new Dictionary<string, MidiTag>();
            this.profileTags = new Dictionary<string, MidiTag>();
            this.newProfileFormat = false;
            this.ampHash = "";
            this.cabHash = "";

            string amp10 = "", amp11 = "", amp21 = "", cab20 = "", cab31 = "", cab41 = "";

            try
            {
                var fs = new FileStream(path, FileMode.Open);
                var len = (int)fs.Length;
                var bits = new byte[len];
                fs.Read(bits, 0, len);
                fs.Close();

                for (int ix = 0; ix < len; ix += 1)
                {
                    var cnt = Math.Min(1, len - ix);
                    var chunk = new byte[cnt];
                    Array.Copy(bits, ix, chunk, 0, cnt);

                    if (!this.inTag)
                    {
                        if (chunk[0] == 0xF0)
                        {
                            //Console.WriteLine("Tag started at index: " + ix);
                            this.inTag = true;
                            this.currentTagStart = (uint)ix;
                        }
                    }
                    else
                    {
                        if (chunk[0] == 0xF7)
                        {
                            //Console.WriteLine("Tag ended at index: " + ix);
                            this.inTag = false;
                            byte[] tagBytes = new byte[ix - currentTagStart];
                            Array.Copy(bits, currentTagStart, tagBytes, 0, ix - currentTagStart);
                            try
                            {
                                MidiTag tag = new MidiTag(tagBytes);
                                if (tag.size != 0)
                                {
                                    this.tags.Add(tag);
                                    switch (tag.typeString)
                                    {
                                        case "Tag":
                                            MidiTag dummy;
                                            if (!tagDict.TryGetValue(tag.idString, out dummy))
                                            {
                                                tagDict.Add(tag.idString, tag);
                                            }
                                            break;
                                        case "Profile":
                                            profileTags.Add(tag.hash, tag);
                                            if (tag.idString.Equals("Amp11") || tag.idString.Equals("Amp21") || tag.idString.Equals("Cab31") || tag.idString.Equals("Cab41"))
                                            {
                                                this.newProfileFormat = true;
                                            }
                                            switch (tag.idString)
                                            {
                                                case "Amp10":
                                                    amp10 = tag.hash;
                                                    break;
                                                case "Amp11":
                                                    amp11 = tag.hash;
                                                    break;
                                                case "Amp21":
                                                    amp21 = tag.hash;
                                                    break;
                                                case "Cab20":
                                                    cab20 = tag.hash;
                                                    break;
                                                case "Cab31":
                                                    cab31 = tag.hash;
                                                    break;
                                                case "Cab41":
                                                    cab41 = tag.hash;
                                                    break;
                                            }
                                            break;
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Error on file " + this.path
                                    + "\r\nTag Data:" + BitConverter.ToString(tagBytes)
                                    , "Error Creating MIDI Tags", MessageBoxButtons.OK);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Exception occurred while trying to create MIDI Tags for file " + this.path
                                    + "\r\nTag Data:" + BitConverter.ToString(tagBytes)
                                    + ".  Exception: " + ex.ToString(), "Error Creating MIDI Tags", MessageBoxButtons.OK);
                            }
                        }
                    }
                }
                if (this.newProfileFormat)
                {
                    this.ampHash = amp11 + amp21;
                    this.cabHash = cab31 + cab41;
                }
                else
                {
                    this.ampHash = amp10;
                    this.cabHash = cab20;
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        public string getAmpAuthor()
        {
            MidiTag ampAuthorTag;
            if (this.tagDict.TryGetValue("Amp Author", out ampAuthorTag))
            {
                return Encoding.ASCII.GetString(ampAuthorTag.data, 0, ampAuthorTag.data.Length - 1);
            }
            return "";
        }

        public string getCabAuthor()
        {
            MidiTag cabAuthorTag;
            if (this.tagDict.TryGetValue("Cab Author", out cabAuthorTag))
            {
                return Encoding.ASCII.GetString(cabAuthorTag.data, 0, cabAuthorTag.data.Length - 1);
            }
            return "";
        }
    }
}
